const recordBtn = document.querySelector(".record-btn");
const recordingPausedBtn = document.querySelector(".recording-paused-btn");
const stopBtn = document.querySelector(".stop-btn");
const player = document.querySelector(".audio-player");
const downloadButton = document.querySelector("#downloadButton");

var myAudio = document.querySelector('.myAudio');

// 混流
var chunks = [];
var mediaRecorder, stream = 2
recordBtn.onclick = async () => {
    if (mediaRecorder) {
        mediaRecorder.start();
        return
    }
    if (navigator.mediaDevices.getUserMedia) {
        var getUserMedia_stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        var getDisplayMedia_stream = await navigator.mediaDevices.getDisplayMedia({
            video: {
                cursor: "never"
            },
            audio: true
        });



/*

        let systemAudioTrack = getDisplayMedia_stream.getAudioTracks()[0]; //获取强制获取的桌面音【轨】
        let audioStream = getUserMedia_stream //获取麦克风音频【流】
        


        let audioContext = new AudioContext(); //创建音频上下文
        let microphoneStreamNode = audioContext.createMediaStreamSource(audioStream); //创建节点
        let sysAudioStream = new MediaStream(); //创建一个媒体流
        sysAudioStream.addTrack(systemAudioTrack); //把系统音轨添加到新的媒体流


        let sysAudioStreamNode = audioContext.createMediaStreamSource(sysAudioStream); //创建系统音频节点



        let mixedOutput = audioContext.createMediaStreamDestination(); //创建一个输出媒体流节点
        microphoneStreamNode.connect(mixedOutput); //把麦克风节点和系统音节点添加到输出媒体流
        sysAudioStreamNode.connect(mixedOutput); //把麦克风节点和系统音节点添加到输出媒体流
        mixedOutput.stream; //返回混合后的媒体流
        */





        let systemAudioTrack = getDisplayMedia_stream //获取强制获取的桌面音【轨】
        let audioStream = getUserMedia_stream //获取麦克风音频【流】
        


        let audioContext = new AudioContext(); //创建音频上下文
        let microphoneStreamNode = audioContext.createMediaStreamSource(audioStream); //创建节点

        let sysAudioStreamNode = audioContext.createMediaStreamSource(systemAudioTrack); //创建系统音频节点
        let myAudioStreamNode = audioContext.createMediaElementSource(myAudio); //创建audio 标签音频节点


        var merger = audioContext.createChannelMerger(2);

        var dest = audioContext.createMediaStreamDestination();//创建一个输出媒体流节点

        microphoneStreamNode.connect(dest)//把麦克风节点和系统音节点添加到输出媒体流
        sysAudioStreamNode.connect(dest)//把麦克风节点和系统音节点添加到输出媒体流
        myAudioStreamNode.connect(dest)//把本地标签音节点添加到输出媒体流


        // merger.connect(dest);



        console.log("授权成功！");
        player.stream = dest.stream


        var options = {
            audioBitsPerSecond: 128000, //比特率为128kbps
            // videoBitsPerSecond : 2500000,
            mimeType: 'audio/webm'
        }

        mediaRecorder = new MediaRecorder(dest.stream, options);

        if (mediaRecorder.state === "recording") {
            mediaRecorder.stop();
            // recordBtn.textContent = "record";
            console.log("录音结束");
        } else {
            mediaRecorder.start();
            console.log("录音中...");
            // recordBtn.textContent = "stop";
        }
        console.log("录音器状态：", mediaRecorder.state);
        console.log("录音比特率：", mediaRecorder.audioBitsPerSecond);


        mediaRecorder.onerror = e => {
            console.log('onerror', e);
        };

        mediaRecorder.onpause = e => {
            console.log('pause', e);
        };

        mediaRecorder.onresume = e => {
            console.log('resume', e);
        };

        mediaRecorder.onstart = e => {
            console.log('start', e);
        };

        mediaRecorder.onwarning = e => {
            console.log('warning', e);
        };

        mediaRecorder.ondataavailable = e => {
            console.log(e)
            chunks.push(e.data);
        };

        mediaRecorder.onstop = e => {
            console.log('onstop')
            var blob = new Blob(chunks, { type: "audio/mp3;" });
            // var blob = new Blob([buffer],{type:'image/png'});// Blob 适合大文件
            var file = new File(chunks, new Date().toLocaleString() + '.mp3') //File 是 的 子类
            chunks = [];
            var audioURL = window.URL.createObjectURL(blob);
            player.src = audioURL;
            player.load();
            downloadButton.href = audioURL;
            downloadButton.download = "audio.mp3";
            console.log(file)
            updateSize(file.size)
            // window.URL.revokeObjectURL(audioURL);
        };

    } else {
        console.error("浏览器不支持 getUserMedia");
    }
};
// 暂停 继续
/*recordingPausedBtn.onclick = function() {
    if (!mediaRecorder) return
    if (mediaRecorder.state === "recording") {
        mediaRecorder.pause();
        // recording paused
    } else if (mediaRecorder.state === "paused") {
        mediaRecorder.resume();
        // resume recording
    }
    console.log("录音器状态：", mediaRecorder.state);
}*/
stopBtn.onclick = () => {
    if (!mediaRecorder) return
    mediaRecorder.stop();
    player.stream.getTracks().forEach(track => track.stop());
    console.log("录音器状态：", mediaRecorder.state);
};

function updateSize(size) {
    let nBytes = size

    let sOutput = nBytes + " bytes";
    // optional code for multiples approximation
    for (let aMultiples = ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"], nMultiple = 0, nApprox = nBytes / 1024; nApprox > 1; nApprox /= 1024, nMultiple++) {
        sOutput = nApprox.toFixed(3) + " " + aMultiples[nMultiple] + " (" + nBytes + " bytes)";
    }
    // end of optional code
    // document.getElementById("fileNum").innerHTML = nFiles;
    // document.getElementById("fileSize").innerHTML = sOutput;
    console.log(sOutput)
}

var fileChange = document.getElementById('fileChooser');
fileChange.onchange = fileChange = (e) => {
    if (e.target.files[0]) {
        let playfile = URL.createObjectURL(e.target.files[0]);
        myAudio.src = playfile;
        // let musicName = e.target.files[0].name.split('.')[0];
        myAudio.load();
        // _audio()
        // file = e.target.files
        // buffer = new Blob(e.target.files, { type: 'audio/mp3' }); // Blob 适合大文件
        // console.log('buffer', buffer)
    }
};
